package com.nbstar.film.spider.spider;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.nbstar.film.spider.filter.ReplaceBracketsNameFilter;
import com.nbstar.film.spider.http.SipderStringRequest;
import com.nbstar.film.spider.pojo.DouBanFilmInfo;
import com.nbstar.film.spider.pojo.FilmInfo;
import com.nbstar.film.spider.filter.*;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.util.*;

@Slf4j
@Data
public class DoubanFilmSpider extends BaseSpider {

    //private static Logger logger = LoggerFactory.getLogger(FilmSpider.class);


    public static final String DOUBAN_BASE_URL = "https://movie.douban.com";

    public DoubanFilmSpider() {
        setRequest(new SipderStringRequest());
        //setRequest(new MoguProxyRequest());
        this.spiderName = "DOUBAN";
        registFilter(new ReplaceBracketsNameFilter());

       // getRequest().addHeader("Proxy-Authorization", "Basic " + Base64.getEncoder().encodeToString("luojing0322@163.com:LUOjing032219860322".getBytes()));
    }

    //@Override
    public String getContentId1(String filmName) throws Exception {
        String url = "https://search.douban.com/movie/subject_search?search_text=" + filmName;

        //String html = getRequest().getHtml(url);
        String html = "";
        if (null != firefoxDriverRequest) {
            html = firefoxDriverRequest.getHtml(url);
        } else {
            html = getRequest().getHtml(url);
        }
        WebDriverWait wait = new WebDriverWait(firefoxDriverRequest.getDriver(), 10);
        WebElement yodaBox = wait.until(ExpectedConditions.presenceOfElementLocated(By.id("detail")));
        html = firefoxDriverRequest.getHtml(url);
        Document document = Jsoup.parse(html);
        Elements detail = document.getElementsByClass("detail");
        if (detail.size() == 0) {
            return "";
        }

        for (Element d : detail) {
            Elements title = d.getElementsByClass("title");
            Elements links = title.select("a[href]");
            for (Element link : links) {
                String href = link.attr("href");
                String name = link.text();
                System.out.println(href + ":" + name);
                if (name.trim().replace(" ", "").equals(filmName.replace(" ", ""))) {
                    return  href;
                }

            }

        }
        return "";
    }

    @Override
    public String getContentId(String filmName)  throws Exception{
        String contentId = "";

        String url = DOUBAN_BASE_URL + "/j/subject_suggest" + "?q=" + filmName;

        String html = getRequest().getHtml(url);

        if (StringUtils.isEmpty(html)) {
            log.error("Error request:" + url);
            return contentId;
        }

//        Document doc = Jsoup.parse(html);
//        Element body = doc.body();
//        html = body.html();

        //String html = HttpRequest.sendGet(url, "q=" + filmName );
        StringBuilder sb = new StringBuilder("{\"result\":");
        sb.append(html);
        sb.append("}");

        System.out.println(sb.toString());

        JSONObject jsonObject = JSON.parseObject(sb.toString());
        JSONArray jsonArray = jsonObject.getJSONArray("result");
        Iterator<Object> iterator = jsonArray.iterator();

        while (iterator.hasNext()) {
            JSONObject object = (JSONObject) iterator.next();
            contentId = (String) object.get("id");
            if (null != contentId) {
                break;
            }
            //stringBuilder.append(object.get("words"));
        }

        return contentId;
    }

    @Override
    public FilmInfo getFilmInfo(String contentId) throws Exception {
        String url = "https://movie.douban.com/subject/" + contentId;
        //String url = contentId;

        DouBanFilmInfo filmInfo = new DouBanFilmInfo();
        if (StringUtils.isEmpty(contentId)) {
            log.error("Error contentid!");
            return filmInfo;
        }

        String html = getRequest().getHtml(url);


        //String html = HttpRequest.sendGet(url, null);
        //System.out.println(html);
        Document document = Jsoup.parse(html);
        //像js一样，通过标签获取title
        //System.out.println(document.getElementsByTag("title").first());
        //像js一样，通过id 获取文章列表元素对象
        Element content = document.getElementById("content");
        if (content == null) {
            log.error("can not found douban content!");
            return filmInfo;
        }

        Elements h1 = content.select("h1");
        System.out.println(h1.text());
        filmInfo.setCname(h1.text());

        Element info = content.getElementById("info");
        //System.out.println(info.text());
        String infos[] = info.text().replace(" / ", ",").split(" ");

        for (int i=0; i<infos.length; i++) {
            if (infos[i].trim().equals("导演:")) {
                i++;
                filmInfo.setDirector(infos[i]);
            }

            if (infos[i].trim().equals("主演:")) {
                i++;
                filmInfo.setActor(infos[i]);
            }

            if (infos[i].trim().equals("制片国家/地区:")) {
                i++;
                filmInfo.setArriveAddress(infos[i]);
            }

            if (infos[i].trim().equals("语言:")) {
                i++;
                filmInfo.setLanguage(infos[i]);
            }

            if (infos[i].trim().equals("上映日期:")) {
                i++;
                filmInfo.setArriveDate(infos[i]);
            }

            if (infos[i].trim().equals("类型:")) {
                i++;
                filmInfo.setCategory(infos[i]);
            }

            if (infos[i].trim().equals("片长:")) {
                i++;
                filmInfo.setFileDuration(infos[i]);
            }

            if (infos[i].trim().equals("又名:")) {
                i++;
                filmInfo.setAliasName(infos[i]);
            }

        }

//        String alias = info.text().substring(info.text().indexOf("又名:") + "又名:".length(), info.text().indexOf("IMDb链接:"));
//        filmInfo.setAliasName(alias);
        Element interest_sectl = document.getElementById("interest_sectl");
        Elements rating_num = interest_sectl.getElementsByClass("ll rating_num");
        Elements rating_people = interest_sectl.getElementsByClass("rating_people");

        double rating = 0.0;
        if (!rating_num.get(0).text().isEmpty()) {
            rating = Double.parseDouble(rating_num.get(0).text());
        }
        //System.out.println();
        long votes = 0;
        if (rating_people.size() > 0) {
            votes = Long.parseLong(rating_people.get(0).text().replace("人评价", ""));
        }

        log.info("rating:" + rating + "  votes:" + votes);
       // Element info = document.getElementById("info");
        Elements links = info.select("a[href]");
        String imdb = "";
        for (Element link : links) {
            String href = link.attr("href");
            if (href.contains("www.imdb.com")) {
                imdb = href;
                break;
            }
        }

        log.info("imdb:" + imdb);


        filmInfo.setImdb(imdb);
        filmInfo.setAverage(rating);
        filmInfo.setVotes(votes);

        Elements runtime = info.getElementsByAttributeValue("property", "v:runtime");
        if (runtime.size() > 0) {
            filmInfo.setFileDuration(runtime.get(0).text());
        }
        Elements initialReleaseDate = info.getElementsByAttributeValue("property", "v:initialReleaseDate");
        if (initialReleaseDate.size() > 0) {
            String[] rdate = initialReleaseDate.get(0).text().split("\\(");
            if (rdate.length >1) {
                filmInfo.setArriveDate(rdate[0]);
                filmInfo.setArriveAddress(rdate[1].replace(")", ""));
            }
        }

        Elements bs = document.getElementsByClass("bs");
        if (bs.size() > 0) {
            Elements li = bs.select("li");
            for (Element e : li) {
                System.out.println(e.text());
                filmInfo.setOnlinePlatform(filmInfo.getOnlinePlatform() + e.text() + ";");
            }
        }

        filmInfo.setSuccess(true);
        return filmInfo;
    }


}
